<?php
/**
 * API调用
 * 
 * @version $Id: Api.php 429 2013-08-02 09:13:14Z linsir123 $
 * @package Common
 */
class lpApi
{
	/**
	 * CRUL数据请求
	 * 
	 * @param string $url 请求地址
	 * @param array $postFields 提交数据
	 * @param bool $useSSL 是否关闭SSL验证
	 * @return mixed
	 * @static 
	 */
	static function curl($url, $postFields = null, $useSSL = false, $timeout = 3)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		if ($useSSL) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}
		
		///
		if (is_array($postFields) && 0 < count($postFields)) {
			$postBodyString = "";
			$postMultipart = false;
			foreach ($postFields as $k => $v) {
				if("@" != substr($v, 0, 1)) 
					// 判断是不是文件上传
					$postBodyString .= "$k=" . urlencode($v) . "&"; 
				else 
					// 文件上传用multipart/form-data，否则用www-form-urlencoded
					$postMultipart = true;
			}
			unset($k, $v);
			
			///
			curl_setopt($ch, CURLOPT_POST, true);
			if ($postMultipart) 
				curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
			else 
				curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
		}
		
		///
		try {
			$reponse = curl_exec($ch);
			if (curl_errno($ch)) 
				throw new Exception("[Curl]". curl_error($ch));
			else {
				$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				if (200 !== $httpStatusCode) 
					throw new Exception("[Curl]". $reponse);
			}
		} catch (Exception $e) {
			///
			return false;
		}
		
		///
		curl_close($ch);
		return $reponse;
	}
}
